<template>
  <el-cascader
    v-model="form[item.key]"
    :props="item.props"
    :disabled="itemDisabled"
    :placeholder="placeholder"
    @change="change"
    clearable
    size="small"
  ></el-cascader>
</template>

<script lang="ts">
import { defineComponent, PropType, ref } from 'vue'
import { Option, Cascader } from '../types'
import { get, find, forEach } from 'lodash'
import usePlaceholder from '@/hooks/usePlacehoder'
import { FormItemKey, ObjectType } from 'typings/interfaces'
import useDisabled from '../hooks/useDisabled'

export default defineComponent({
  props: {
    item: {
      type: Object as PropType<Cascader>,
      required: true,
    },
    form: {
      type: Object as PropType<ObjectType>,
      required: true,
    },
    options: {
      type: Object as PropType<Record<FormItemKey, Option[]>>,
      required: true,
    },
    disabled: {
      type: Boolean,
      required: true,
    },
  },
  setup(props) {
    const placeholder = usePlaceholder(props.item, 'lang.placeholder.select')
    const itemDisabled = useDisabled(props.disabled, props.item.disabled)
    const key = get(props, 'item.alias') ?? get(props, 'item.key', '')
    const option = ref<Option[]>(get(props.options, [props.item.key], []))

    // 动态修改其他表单项
    const change = (value: string) => {
        const row = find(option.value, { [key]: value })
        forEach(props.item.shouldUpdate, ([key, alias]) => {
          props.form[key] = get(row, alias ?? key)
        })
    }

    return { itemDisabled,placeholder,change }
  },
})
</script>
